package com.nlp.server.factory;

import com.nlp.server.properties.ChatProperties;
import com.nlp.server.strategy.ChatQuery;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 查询策略的上下文工具类
 * @author shiliuyinzhen
 */
@Component
public class ChatQueryFactory implements ApplicationContextAware {

    @Autowired
    private ChatProperties chatProperties;

    private static Map<String, ChatQuery> chatQueryPool = new HashMap<String, ChatQuery>();

    /**
     * 从配置文件中读取查询策略的信息
     * {
     *     text: textQuery
     *     voice: voiceQuery
     * }
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        chatProperties.getQueryTypes().forEach((k, v) -> {
            //通过字符串找到对应的Bean
            chatQueryPool.put(k,(ChatQuery)applicationContext.getBean(v));
        });
    }

    /**
     * 通过不同的查询类型，返回对应的策略对象
     * @param queryType 查询类型,需要和配置文件保持一致
     * @return 具体策略对象
     */
    public ChatQuery getChatQuery(String queryType) {
        return chatQueryPool.get(queryType);
    }
}
